package com.tambapps.p2p.fandem.handshake

import com.tambapps.p2p.fandem.Fandem
import com.tambapps.p2p.speer.exception.HandshakeFailException
import com.tambapps.p2p.speer.handshake.SerializedHandshake
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException

class FandemReceiverHandshake @JvmOverloads constructor(data: ReceiverHandshakeData? = ReceiverHandshakeData()) :
    SerializedHandshake<ReceiverHandshakeData?, SenderHandshakeData>(
        Fandem.serializer(), Fandem.deserializer(
            SenderHandshakeData::class.java
        ), data
    ) {

    @Throws(IOException::class)
    override fun apply(outputStream: DataOutputStream, inputStream: DataInputStream): Any {
        outputStream.writeUTF("FANDEM")
        outputStream.writeUTF(Fandem.VERSION)
        if (inputStream.readUTF() != "FANDEM") {
            throw HandshakeFailException("Remote peer is not a fandem peer")
        }
        val version = inputStream.readUTF()
        Fandem.checkVersionCompatibility(version)
        serializer.serialize(data, outputStream)
        val senderHandshakeData = deserializer.deserialize(inputStream)
        validate(senderHandshakeData)
        return senderHandshakeData
    }

    @Throws(HandshakeFailException::class)
    override fun validate(senderHandshakeData: SenderHandshakeData) {
        senderHandshakeData.validate()
    }
}
